package com.tencent.liteav.demo.play.controller;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.liteav.demo.play.R;
import com.tencent.liteav.demo.play.SuperPlayerConst;
import com.tencent.liteav.demo.play.view.TCPointSeekBar;
import com.tencent.liteav.demo.play.view.TCVideoProgressLayout;
import com.tencent.liteav.demo.play.view.TCVolumeBrightnessProgressLayout;

/**
 * Created by liyuejiao on 2018/7/3.
 * <p>
 * 超级播放器小窗口控制界面
 */
public class TCVodControllerSmall extends TCVodControllerBase implements View.OnClickListener {
    private static final String TAG = "TCVodControllerSmall";
    private LinearLayout mLayoutTop;
    private LinearLayout mLayoutBottom;
    private ImageView mIvPause;
    private ImageView mIvFullScreen;
//    private TextView mTvCurrent;
//    private TextView mTvDuration;
//    private SeekBar mSeekBarProgress;
    private TextView mTvTitle;
//    private LinearLayout mLayoutReplay;
    private TextView mTvBackToLive;
//    private ProgressBar mPbLiveLoading;

    //=======================2019-8-23新增====================
    private AppCompatTextView mAudioVideoChangeBtn;
    private ImageView leftRretreatBtn;
    private ImageView rightSpeedBtn;
    private AnimationDrawable animationDrawable;
    private Animation roteAnimation;
    //=======================2019-8-23新增====================

    public TCVodControllerSmall(Context context) {
        super(context);
        initViews();
    }

    public TCVodControllerSmall(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews();
    }

    public TCVodControllerSmall(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViews();
    }

    /**
     * 显示播放控制界面
     */
    @Override
    void onShow() {
        mLayoutTop.setVisibility(View.VISIBLE);
        mLayoutBottom.setVisibility(View.VISIBLE);

        if (mPlayType == SuperPlayerConst.PLAYTYPE_LIVE_SHIFT) {
            mTvBackToLive.setVisibility(View.VISIBLE);
        }
        //============================2019-8-26新增====================
        if( resourseType == SuperPlayerConst.RESOURCE_TYPE_VIDEO ){
            if (1==SuperPlayerConst.CAN_CHANGE_LARGE) {
                mIvFullScreen.setVisibility(GONE);
            }else {
                mIvFullScreen.setVisibility(VISIBLE);
            }
        }else{
            mIvFullScreen.setVisibility( GONE );
        }
        //============================2019-8-26新增====================
    }

    /**
     * 隐藏播放控制界面
     */
    @Override
    void onHide() {
        mLayoutTop.setVisibility(View.GONE);
        //============================2019-10-22修改========新增判断============
        if( isAwayShow ){
            mLayoutBottom.setVisibility(View.VISIBLE);
        }else{
            mLayoutBottom.setVisibility(View.GONE);
        }
        //============================2019-10-22修改====================

        if (mPlayType == SuperPlayerConst.PLAYTYPE_LIVE_SHIFT) {
            mTvBackToLive.setVisibility(View.GONE);
        }
    }

    /**
     * 进度定时器
     */
//    @Override
//    void onTimerTicker() {
//        switch (mPlayType) {
//            case SuperPlayerConst.PLAYTYPE_VOD:
//                updateVodVideoProgress();
//                break;
//            case SuperPlayerConst.PLAYTYPE_LIVE:
//                mTvCurrent.setText(TCTimeUtils.formattedTime(mLivePlayTime));
//                break;
//            case SuperPlayerConst.PLAYTYPE_LIVE_SHIFT:
//                mTvCurrent.setText(TCTimeUtils.formattedTime(mLiveShiftTime));
//                break;
//        }
//    }

    private void initViews() {
        mLayoutInflater.inflate(R.layout.vod_controller_small, this);

        //=====================2019-8-23新增================
        rootLayout = findViewById( R.id.vod_controller_small_root_layout );
        imageContainer = findViewById( R.id.layout_yp_state_image_container );
        mAudioVideoChangeBtn = findViewById( R.id.void_controller_small_audio_vidio_change_btn );
        mAudioVideoChangeBtn.setOnClickListener( this );

        leftRretreatBtn = findViewById( R.id.vod_controller_small_left_retreat_btn );
        leftRretreatBtn.setOnClickListener( this );
        rightSpeedBtn = findViewById( R.id.vod_controller_small_right_speed_btn );
        rightSpeedBtn.setOnClickListener( this );
        ypStateImg = findViewById( R.id.layout_yp_state_image );
//        ypStateImg.setImageResource( R.drawable.super_player_view_yp_img_drawable );
        ypStateImg.setImageResource( R.mipmap.icon_progress );
        //=====================2019-8-23新增================

        mLayoutTop = (LinearLayout) findViewById(R.id.layout_top);
        mLayoutTop.setOnClickListener(this);
        mLayoutBottom = (LinearLayout) findViewById(R.id.layout_bottom);
        mLayoutBottom.setOnClickListener(this);
        mLayoutReplay = (LinearLayout) findViewById(R.id.layout_replay);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mIvPause = (ImageView) findViewById(R.id.iv_pause);
        mTvCurrent = (TextView) findViewById(R.id.tv_current);
        mTvDuration = (TextView) findViewById(R.id.tv_duration);
        mSeekBarProgress = (TCPointSeekBar) findViewById(R.id.seekbar_progress);
        mSeekBarProgress.setProgress(0);
        mSeekBarProgress.setMax(100);
        mIvFullScreen = (ImageView) findViewById(R.id.iv_fullscreen);
        mTvBackToLive = (TextView) findViewById(R.id.tv_backToLive);
        mPbLiveLoading = (ProgressBar) findViewById(R.id.pb_live);

        mTvBackToLive.setOnClickListener(this);
        mIvPause.setOnClickListener(this);
        mIvFullScreen.setOnClickListener(this);
        mLayoutTop.setOnClickListener(this);
        mLayoutReplay.setOnClickListener(this);

        mSeekBarProgress.setOnSeekBarChangeListener(this);

        mGestureVolumeBrightnessProgressLayout = (TCVolumeBrightnessProgressLayout)findViewById(R.id.gesture_progress);

        mGestureVideoProgressLayout = (TCVideoProgressLayout) findViewById(R.id.video_progress_layout);
    }


    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.layout_top) {
            //============================2019-10-29-15-45注释=====================
            //点击视频顶部，会多出一部分
//            onBack();
            //============================2019-10-29-15-45注释=====================

        } else if (i == R.id.iv_pause) {
            //==============================2019-11-15-15-41新增=================
            if( mVodController.isPlaying() ){
                isManualPause = true;
            }else{
                isManualPause = false;
            }
            //==============================2019-11-15-15-41新增=================
            changePlayState();
        } else if (i == R.id.iv_fullscreen) {
            fullScreen();

        } else if (i == R.id.layout_replay) {
            replay();

        } else if (i == R.id.tv_backToLive) {
            backToLive();

        }else if(i == R.id.void_controller_small_audio_vidio_change_btn ){
            //音视频切换按钮
            audioVideoChange( false ,true , true ,true );
        }else if( i == R.id.vod_controller_small_left_retreat_btn ){
            //左边倒退
            float currentPlaybackTime = mVodController.getCurrentPlaybackTime();
            if( currentPlaybackTime < 15  ){
                mVodController.seekTo( 0 );
                return;
            }
            mVodController.seekTo( (int)(currentPlaybackTime - 15) );
        }else if( i == R.id.vod_controller_small_right_speed_btn ){
            //快进
            float currentPlaybackTime = mVodController.getCurrentPlaybackTime();
            float duration = mVodController.getDuration();
            if( duration - currentPlaybackTime < 15 ){
                mVodController.seekTo( (int)duration );
                return;
            }
            mVodController.seekTo( (int)(currentPlaybackTime + 15) );
        }
    }

    //==========================2019-8-23新增===================
    /**
     * 显示加载进度
     */
    public void showLoadingProgress( boolean isShowLoading ){
        if( ypStateImg != null ){
            if( isShowLoading ){
                rootLayout.setBackgroundColor( getContext().getResources().getColor( R.color.color_80000000));
                ypStateImg.setVisibility( VISIBLE );
                imageContainer.setVisibility( VISIBLE );
                roteAnimation = rotateViewRepeat( ypStateImg );
//            startAnimList();
            }else{
                rootLayout.setBackgroundColor( getContext().getResources().getColor( R.color.transparent));
                if( roteAnimation != null ){
                    roteAnimation.cancel();
                }
                ypStateImg.setVisibility( GONE );
                imageContainer.setVisibility( GONE );
//            stopAnimList();
            }
        }
    }

    /**
     * 旋转view
     * @param view
     */
    private Animation rotateViewRepeat( View view ){
        Animation roteAnimation = new RotateAnimation(0.0f, 360f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        roteAnimation.setRepeatCount(-1);
        roteAnimation.setInterpolator(new LinearInterpolator());
        roteAnimation.setDuration(2000);
        view.startAnimation(roteAnimation);
        return roteAnimation;
    }

    public void audioVideoChange( boolean isLive ,  boolean isCanChange , boolean isVideo , boolean isShowCover ){
        if( isLive ){
            mAudioVideoChangeBtn.setVisibility( GONE );
//            rootLayout.setBackgroundColor( getContext().getResources().getColor( R.color.transparent));
            if (1==SuperPlayerConst.CAN_CHANGE_LARGE) {
                mIvFullScreen.setVisibility(GONE);
            }else {
                mIvFullScreen.setVisibility(VISIBLE);
            }
            leftRretreatBtn.setVisibility( GONE );
            rightSpeedBtn.setVisibility( GONE );
//            ypStateImg.setVisibility( GONE );
        }else if( isCanChange ){
//            mAudioVideoChangeBtn.setVisibility( VISIBLE );//音视频播放提示，右上角
            mIvFullScreen.setVisibility( VISIBLE );
            leftRretreatBtn.setVisibility( GONE );
            rightSpeedBtn.setVisibility( GONE );
        }else{
            mAudioVideoChangeBtn.setVisibility( GONE );
            if( isVideo ){
                leftRretreatBtn.setVisibility( GONE );
                rightSpeedBtn.setVisibility( GONE );
            }else{
                leftRretreatBtn.setVisibility( VISIBLE );
                rightSpeedBtn.setVisibility( VISIBLE );
            }
//            rootLayout.setBackgroundColor( getContext().getResources().getColor( R.color.color_80000000));
//            ypStateImg.setVisibility( VISIBLE );
        }
        mVodController.audioVideoChange( isLive ,  isCanChange , isShowCover );
    }

    public void updateAudioVideoState( boolean isLive , boolean isVideo ) {
        if( isVideo ){
            isAwayShow = false;
            mVodController.playResourceMode( true );
            mAudioVideoChangeBtn.setText( getResources().getString( R.string.audio_play ) );
//            rootLayout.setBackgroundColor( getContext().getResources().getColor( R.color.color_00000000));
            mIvFullScreen.setVisibility( VISIBLE );
            leftRretreatBtn.setVisibility( GONE );
            rightSpeedBtn.setVisibility( GONE );
//            ypStateImg.setVisibility( GONE );
        }else{
            isAwayShow = true;
            mVodController.playResourceMode( false );
            mAudioVideoChangeBtn.setText( getResources().getString( R.string.video_play ) );
//            rootLayout.setBackgroundColor( getContext().getResources().getColor( R.color.color_80000000));
            mIvFullScreen.setVisibility( GONE );
            leftRretreatBtn.setVisibility( VISIBLE );
            rightSpeedBtn.setVisibility( VISIBLE );
//            ypStateImg.setVisibility( VISIBLE );
//            startAnimList();
        }
    }
    //==========================2019-8-23新增===================

    /**
     * 返回直播
     */
    private void backToLive() {
        mVodController.resumeLive();
    }



    /**
     * 返回窗口模式
     */
    private void onBack() {
        mVodController.onBackPress(SuperPlayerConst.PLAYMODE_WINDOW);
    }

    /**
     * 全屏
     */
    private void fullScreen() {
        mVodController.onRequestPlayMode(SuperPlayerConst.PLAYMODE_FULLSCREEN);
    }



//    @Override
//    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
//
//    }
//
//    @Override
//    public void onStartTrackingTouch(SeekBar seekBar) {
//
//    }
//
//    @Override
//    public void onStopTrackingTouch(SeekBar seekBar) {
//        // 拖动seekbar结束时,获取seekbar当前进度,进行seek操作,最后更新seekbar进度
//        int curProgress = seekBar.getProgress();
//        int maxProgress = seekBar.getMax();
//
//        switch (mPlayType) {
//            case SuperPlayerConst.PLAYTYPE_VOD:
//                if (curProgress >= 0 && curProgress < maxProgress) {
//                    // 关闭重播按钮
//                    updateReplay(false);
//                    float percentage = ((float) curProgress) / maxProgress;
//                    int position = (int) (mVodController.getDuration() * percentage);
//                    mVodController.seekTo(position);
//                    mVodController.resume();
//                }
//                break;
//            case SuperPlayerConst.PLAYTYPE_LIVE:
//            case SuperPlayerConst.PLAYTYPE_LIVE_SHIFT:
//                updateLiveLoadingState(true);
////                mTrackTime = mLivePlayTime * curProgress / maxProgress;
//                TXCLog.i(TAG, "onStopTrackingTouch time:" + mTrackTime);
////                mVodController.onBackToRecord(mLiveBaseTime, mTrackTime);
//                break;
//        }
//    }

    /**
     * 更新直播加载ProgressBar状态
     *
     * @param loading
     */
//    public void updateLiveLoadingState(boolean loading) {
//        if (loading) {
//            mPbLiveLoading.setVisibility(View.VISIBLE);
//        } else {
//            mPbLiveLoading.setVisibility(View.GONE);
//        }
//    }

    /**
     * 更新点播播放进度
     */
//    public void updateVodVideoProgress() {
//        float curTime = mVodController.getCurrentPlaybackTime();
//        float durTime = mVodController.getDuration();
//
//        if (durTime > 0 && curTime <= durTime) {
//            float percentage = curTime / durTime;
//            if (percentage >= 0 && percentage <= 1) {
//                int progress = Math.round(percentage * mSeekBarProgress.getMax());
//                mSeekBarProgress.setProgress(progress);
//
//                if (durTime >= 0 && curTime <= durTime) {
//                    mTvCurrent.setText(TCTimeUtils.formattedTime((long) curTime));
//                    mTvDuration.setText(TCTimeUtils.formattedTime((long) durTime));
//                }
//            }
//        }
//    }

    /**
     * 更新播放UI
     *
     * @param isStart
     */
    public void updatePlayState(boolean isStart) {
        // 播放中
        if (isStart) {
            mIvPause.setImageResource(R.drawable.ic_vod_pause_normal);
        }
        // 未播放
        else {
            mIvPause.setImageResource(R.drawable.ic_vod_play_normal);
        }
    }

    /**
     * 更新标题
     *
     * @param title
     */
    public void updateTitle(String title) {
        super.updateTitle(title);
        mTvTitle.setText(mTitle);
    }

    /**
     * 更新重新播放按钮状态
     *
     * @param replay
     */
//    public void updateReplay(boolean replay) {
//        if (replay) {
//            mLayoutReplay.setVisibility(View.VISIBLE);
//        } else {
//            mLayoutReplay.setVisibility(View.GONE);
//        }
//    }

//    /**
//     * 更新直播播放时间和进度
//     *
//     * @param baseTime
//     */
//    public void updateLivePlayTime(long baseTime) {
//        super.updateLivePlayTime(baseTime);
//        mTvCurrent.setText(TCTimeUtils.formattedTime(mLivePlayTime));
//    }

    /**
     * 更新直播回看播放时间
     *
     * @param liveshiftTime
     */
//    public void updateLiveShiftPlayTime(long liveshiftTime) {
//        super.updateLiveShiftPlayTime(liveshiftTime);
//        mTvCurrent.setText(TCTimeUtils.formattedTime(mLiveShiftTime));
//    }

    /**
     * 更新播放类型
     *
     * @param playType
     */
    public void updatePlayType(int playType) {
        TXCLog.i(TAG, "updatePlayType playType:" + playType);
        super.updatePlayType(playType);
        switch (playType) {
            case SuperPlayerConst.PLAYTYPE_VOD:
                mTvBackToLive.setVisibility(View.GONE);
                mTvDuration.setVisibility(View.VISIBLE);
                break;
            case SuperPlayerConst.PLAYTYPE_LIVE:
                mTvBackToLive.setVisibility(View.GONE);
                mTvDuration.setVisibility(View.GONE);
                mSeekBarProgress.setProgress(100);
                break;
            case SuperPlayerConst.PLAYTYPE_LIVE_SHIFT:
                if (mLayoutBottom.getVisibility() == VISIBLE)
                    mTvBackToLive.setVisibility(View.VISIBLE);
                mTvDuration.setVisibility(View.GONE);
                break;
        }
    }

    //=====================2019-8-27新增===============
    /**
     * 开始帧动画
     */
    private void startAnimList(){
        animationDrawable = (AnimationDrawable) ypStateImg.getDrawable();
        if( animationDrawable == null ){
            return;
        }
        animationDrawable.start();
    }

    /**
     * 停止动画
     */
    public void stopAnimList(){
        animationDrawable = (AnimationDrawable) ypStateImg.getDrawable();
        if( animationDrawable == null ){
            return;
        }
        animationDrawable.stop();
    }
    //=====================2019-8-27新增===============


    public ImageView getChangeLarge(){
        return mIvFullScreen;
    }

}
